import { BanList } from "./BanList";
import { Com } from "./com";
import { Config } from "./utils/config";

class Inject2 {
  regList: RegExp[] = [];
  com: null | Com = null;
  banList: BanList = new BanList();
  config: Config = new Config();

  constructor() {
    this.config.onChange((configs) => {
      this.ignoreNotExist(this.com, (com) => {
        com.dispatch({
          type: "configChange",
          data: configs,
        });
      });
    });
    window.addEventListener("DOMContentLoaded", () => {
      // console.log("DOMContentLoaded", "iso");
      this.com = Com.getInstance("isolated", "main");
      this.com.setReceiver(({ data, type }) => {
        // console.log(data, type, "iso");
        switch (type) {
          case "getConfig":
            this.exist(this.com, (com) => {
              com.dispatch({
                type: "getConfig",
                data: this.config.getConfig(),
              });
            });
            break;
          case "reset":
            setTimeout(() => {
              this.exist(this.com, (com) => {
                com.reset();
                com.dispatch({
                  type: "updateList",
                  data: this.banList.getList(),
                });
                com.dispatch({
                  type: "getConfig",
                  data: this.config.getConfig(),
                });
              });
            }, 0);
            break;
        }
      });
      this.banList
        .init((list) => {
          //on change event:
          this.exist(this.com, (com) => {
            com.dispatch({
              type: "updateList",
              data: list,
            });
          });
        })
        .then(() => {
          // first time
          this.exist(this.com, (com) => {
            com.dispatch({
              type: "updateList",
              data: this.banList.getList(),
            });
          });
        });
    });
  }
  ignoreNotExist<T>(entity: T | null, success: (en: T) => void) {
    if (entity) success(entity);
  }
  exist<T>(entity: T | null, success: (en: T) => void) {
    if (!entity) {
      console.trace("entity does not exist!", entity);
      return;
    }
    success(entity);
  }
}

const inject = new Inject2();
